<?php
// require_once '../admin_check.php';
// admin/index.php
require_once '../config.php';      // 先引入数据库连接
require_once '../admin_check.php'; // 再验证权限

// 获取用户数据
try {
    $stmt = $pdo->query("SELECT * FROM users ORDER BY id ASC");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("数据库查询失败: " . $e->getMessage());
}

// 用户管理逻辑
$stmt = $pdo->query("SELECT * FROM users ORDER BY id ASC");
$users = $stmt->fetchAll();
?>

<?php include '../includes/header.php'; ?>
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h4>用户管理系统</h4>
        <a href="add_user.php" class="btn btn-success">添加新用户</a>
    </div>
    <div class="card-body">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>角色</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $user): ?>
                <tr>
                    <td><?= $user['id'] ?></td>
                    <td><?= htmlspecialchars($user['username']) ?></td>
                    <td><?= htmlspecialchars($user['email']) ?></td>
                    <td><?= $user['role'] ?></td>
                    <td>
                        <a href="edit_user.php?id=<?= $user['id'] ?>" class="btn btn-sm btn-primary">修改</a>
                        <form action="delete_user.php" method="POST" style="display:inline;">
                            <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                            <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('确定删除此用户?')">删除</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <a href="../profile.php" class="btn btn-secondary">退出</a>
</div>
<?php include '../includes/footer.php'; ?>